package com.hzsk.lisence.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzsk.lisence.config.AnnotationForLog;
import com.hzsk.lisence.config.MyConfig;
import com.hzsk.lisence.entity.LisenceUserEntity;
import com.hzsk.lisence.entity.LisenceUserGrouping;
import com.hzsk.lisence.entity.LogEnum;
import com.hzsk.lisence.entity.UserRole;
import com.hzsk.lisence.entity.query.LisenceServiceQuery;
import com.hzsk.lisence.entity.response.IncResponce;
import com.hzsk.lisence.mapper.LisenceUserMapper;
import com.hzsk.lisence.service.UserService;
import com.hzsk.lisence.util.EncipherUtils;
import com.hzsk.lisence.util.JwtUtils;
import com.hzsk.lisence.util.RsaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    private LisenceUserMapper lisenceUserMapper;


    @Override
    @AnnotationForLog(operationType = LogEnum.SAVE_GROUPING,operation = "保存组织信息",operationalEntity = "LisenceUserGrouping.java/STUDENT_T")
    public void createGroupingByAdmin(LisenceUserGrouping lisenceUserGrouping,Integer userId,IncResponce incResponce) {
        String groupingName = lisenceUserGrouping.getGroupingName();
        if (StringUtils.isBlank(groupingName)){
            incResponce.setCode(1);
            incResponce.setErrorMessage("请求参数异常");
            return;
        }
        List<LisenceUserGrouping> userGroupingList = lisenceUserMapper.getUserGroupingList(groupingName);
        if (userGroupingList.size() > 0){
            incResponce.setCode(1);
            incResponce.setErrorMessage("组织名称重复");
            return;
        }
        lisenceUserMapper.createGroupingByAdmin(lisenceUserGrouping);
        incResponce.setCode(0);
        incResponce.setErrorMessage("操作成功");
    }

    @Override
    public Object getUserGroupingList(LisenceServiceQuery lisenceServiceQuery) {
        PageHelper.startPage(lisenceServiceQuery.getPageNum(), lisenceServiceQuery.getPageSize());
        List<LisenceUserGrouping> infos =  lisenceUserMapper.getUserGroupingList(null);
        return new PageInfo<>(infos);
    }

    @Override
    @AnnotationForLog(operationType = LogEnum.UPDATE_GROUPING,operation = "修改组织信息",operationalEntity = "LisenceUserGrouping.java/STUDENT_T")
    public void updateUserGroupingInfo(LisenceUserGrouping lisenceUserGrouping,Integer userId,IncResponce incResponce) {
        String groupingName = lisenceUserGrouping.getGroupingName();
        if (StringUtils.isBlank(groupingName)){
            incResponce.setCode(1);
            incResponce.setErrorMessage("请求参数异常");
            return;
        }
        List<LisenceUserGrouping> userGroupingList = lisenceUserMapper.getUserGroupingList(groupingName);
        if (userGroupingList.size() >= 1 && !Objects.equals(userGroupingList.get(0).getId(), lisenceUserGrouping.getId())){
            incResponce.setCode(1);
            incResponce.setErrorMessage("组织名称重复");
            return;
        }
        lisenceUserMapper.updateUserGroupingInfo(lisenceUserGrouping);
        incResponce.setCode(0);
        incResponce.setErrorMessage("操作成功");
    }

    @Override
    @AnnotationForLog(operationType = LogEnum.DEL_GROUPING,operation = "删除组织信息",operationalEntity = "LisenceUserGrouping.java/STUDENT_T")
    public void delUserGroupingInfo(Integer id,Integer userId,IncResponce incResponce) {
        List<LisenceUserEntity> lisenceUserEntities = lisenceUserMapper.selectEntityByGroupingId(id);
        if (lisenceUserEntities.size() > 0){
            incResponce.setCode(1);
            incResponce.setErrorMessage("组织存着管理员");
        }else {
            lisenceUserMapper.delUserGroupingInfo(id);
            incResponce.setCode(0);
            incResponce.setData("操作成功");
        }
    }


    /**
     * 用户登录模块
     * @param entity 用户参数
     * @return 返回token
     */
    @Override
    @AnnotationForLog(operationType = LogEnum.LOGIN,operation = "用户登录",operationalEntity = "LisenceUserEntity.java/STUDENT_T")
    public LisenceUserEntity userLogin(LisenceUserEntity entity,Integer userId) throws Exception {
        PrivateKey privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile(MyConfig.PRI).getPath());
        entity.setToken(JwtUtils.generateTokenExpireInMinutes(entity, privateKey, 180));
        return entity;
    }

    @Override
    @AnnotationForLog(operationType = LogEnum.UPDATE_USER,operation = "修改用户信息",operationalEntity = "LisenceUserEntity.java/STUDENT_T")
    public void updateUserInfo(LisenceUserEntity lisenceUserEntity,Integer userId,IncResponce incResponce) {
        String userName = lisenceUserEntity.getUserName();
        if (StringUtils.isBlank(userName)){
            incResponce.setCode(1);
            incResponce.setErrorMessage("请求参数异常");
            return;
        }
        List<LisenceUserEntity> lisenceUserEntities = lisenceUserMapper.selectEntityByName(userName);
        if (lisenceUserEntities.size() >= 1 && !Objects.equals(lisenceUserEntities.get(0).getUserId(), lisenceUserEntity.getUserId())){
            incResponce.setCode(1);
            incResponce.setErrorMessage("客户名称不能重复");
            return;
        }
        String password = lisenceUserEntity.getPassword();
        if (StringUtils.isNoneBlank(password)) lisenceUserEntity.setPassword(EncipherUtils.encrypted(password));
        lisenceUserMapper.updateUserInfo(lisenceUserEntity);
        incResponce.setCode(0);
        incResponce.setErrorMessage("操作成功");
    }

    @Override
    @AnnotationForLog(operationType = LogEnum.DEL_USER,operation = "删除用户",operationalEntity = "LisenceUserEntity.java/STUDENT_T")
    public String delUserinfo(Integer id,Integer userId) {
        lisenceUserMapper.delUserinfo(id);
        return "操作成功";
    }

    @Override
    @AnnotationForLog(operationType = LogEnum.PASSWORD_RESET,operation = "密码重置",operationalEntity = "LisenceUserEntity.java/STUDENT_T")
    public String setPasswordReset(Integer userId, Integer operatorUserId) {
        lisenceUserMapper.setPasswordReset(EncipherUtils.encrypted(MyConfig.PASSWORD_RESET),userId );
        return "操作成功";
    }


    @Override
    public void getUserList(LisenceServiceQuery lisenceServiceQuery,IncResponce incResponce) {
        PageHelper.startPage(lisenceServiceQuery.getPageNum(), lisenceServiceQuery.getPageSize());
        List<LisenceUserEntity> infos =  lisenceUserMapper.getUserList(lisenceServiceQuery);
        infos.stream().map(item->{
            item.setPassword(EncipherUtils.decrypt(item.getPassword()));
            return item;
        });
        incResponce.setCode(0);
        incResponce.setData( new PageInfo<>(infos));

//        Integer userId = lisenceServiceQuery.getUserId();
//        LisenceUserEntity lisenceUserEntity = lisenceUserMapper.selectEntityById(userId);
//        String userRole = lisenceUserEntity.getUserRole();
//        if (userRole.equals(UserRole.EMPOWER.toString()) && lisenceServiceQuery.getUserRole().equals(UserRole.ORDINARY.toString())
//        || userRole.equals(UserRole.SUPER.toString())){
//            PageHelper.startPage(lisenceServiceQuery.getPageNum(), lisenceServiceQuery.getPageSize());
//            List<LisenceUserEntity> infos =  lisenceUserMapper.getUserList(lisenceServiceQuery);
//            incResponce.setCode(0);
//            incResponce.setData( new PageInfo<>(infos));
//        } else {
//            incResponce.setCode(-1);
//            incResponce.setData("无权限查看");
//        }
    }

    @Override
    @AnnotationForLog(operationType = LogEnum.CREATE_USER,operation = "创建用户",operationalEntity = "LisenceUserEntity.java/STUDENT_T")
    public String saveLisenceUser(LisenceUserEntity lisenceUserEntity,Integer userId) {
        String password = lisenceUserEntity.getPassword();
        if (!StringUtils.isEmpty(password)){
            lisenceUserEntity.setPassword(EncipherUtils.encrypted(password));
        }
        lisenceUserMapper.saveLisenceUser(lisenceUserEntity);
        return "操作成功";
    }




}
